import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:xinxuan/common/address_bar.dart';
import 'package:xinxuan/common/appbar_util.dart';
import 'package:get/get.dart';
import 'package:xinxuan/common/button_util.dart';
import 'package:xinxuan/common/dialogs/del_dialog.dart';
import 'package:xinxuan/common/goods_order_info_item.dart';
import 'package:xinxuan/common/network_image_util.dart';
import 'package:xinxuan/common/scroll_configuration_common.dart';
import 'package:xinxuan/common/store_order_btns.dart';
import 'package:xinxuan/config/app_config.dart';
import 'package:xinxuan/controllers/common_page_controller.dart';
import 'package:xinxuan/controllers/store_order_controller/store_order_detail_page_controller.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:xinxuan/router/app_routers.dart';
import 'package:xinxuan/utils/color_util.dart';
import 'package:common_utils/common_utils.dart';

class StoreOrderDetailPage extends StatelessWidget {
  
  final CommonPageController commonPageController = Get.find();

  @override
  Widget build(BuildContext context) {
    Map<String, dynamic> argumentsMap = Get.arguments;
    String title = argumentsMap['title'];
    int orderId = argumentsMap['orderId'];
    return GetBuilder<StoreOrderDetailPageController>(
      init: StoreOrderDetailPageController(),
      builder: (controller) {
        return Scaffold(
          backgroundColor: pageBgColor,
          appBar: AppBarUtil(
            title: title,
            backgroundColor: pageBgColor,
          ),
          body: controller.orderDetailData.value.id! <= 0 ? Container() : ScrollConfigurationCommon(child: ListView(
            children: [
              controller.orderDetailData.value.pickType == 1 && controller.orderDetailData.value.status == 1 ? Container(
                margin: EdgeInsets.only(bottom: 12.h),
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                color: bgWhiteColor,
                child: Container(
                  height: 70.h,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(
                        'assets/images/image_delivery_voucher.png',
                      ),
                      fit: BoxFit.fill
                    )
                  ),
                ),
              ) : controller.orderDetailData.value.pickType == 1 && controller.orderDetailData.value.status != 1 ? Container() : Column(
                children: [
                  AddressBar(
                    consignee: controller.orderDetailData.value.address!.consignee ?? '', 
                    mobile: controller.orderDetailData.value.address!.mobile ?? '', 
                    provinceStr: controller.orderDetailData.value.address!.provinceStr ?? '', 
                    cityStr: controller.orderDetailData.value.address!.cityStr ?? '', 
                    districtStr: controller.orderDetailData.value.address!.districtStr ?? '', 
                    address: controller.orderDetailData.value.address!.address ?? '', 
                    id: 1,
                    showRight: false,
                  ),
                  SizedBox(height: 12.h),
                ],
              ),
              Container(
                color: bgWhiteColor,
                child: Column(
                  children: [
                    Container(
                      height: 44.h,
                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                      alignment: Alignment.center,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(
                            '商品信息',
                            style: TextStyle(
                              color: textBlackColor,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.bold
                            ),
                          ),
                          Text(
                            '${controller.orderDetailData.value.statusStr}',
                            style: TextStyle(
                              color: mainTextColor,
                              fontSize: 14.sp
                            ),
                          )
                        ],
                      ),
                    ),
                    Column(
                      children: controller.orderDetailData.value.products!.map((productItem) {
                        return _goodsInfo(
                          productItem.title ?? '', 
                          productItem.image ?? '', 
                          productItem.price ?? '', 
                          productItem.quantity ?? 0, 
                          productItem.specStr ?? '',
                          controller.orderDetailData.value.integral ?? 0
                        );
                      }).toList(),
                    ),
                    controller.orderDetailData.value.pickType == 1 && !TextUtil.isEmpty(controller.orderDetailData.value.voucherCode) ? Container(
                      width: 375.w,
                      padding: EdgeInsets.symmetric(vertical: 12.h),
                      decoration: BoxDecoration(
                        border: Border(
                          top: BorderSide(
                            color: lineColor,
                            width: .5
                          )
                        )
                      ),
                      child: Column(
                        children: [
                          Stack(
                            children: [
                              Container(
                                width: 230.w,
                                padding: EdgeInsets.symmetric(vertical: 8.h),
                                alignment: Alignment.center,
                                child: Opacity(
                                  opacity: controller.orderDetailData.value.status == 8 ? .3 : 1,
                                  child: QrImage(
                                    data: controller.orderDetailData.value.writeoffUrl ?? AppConfig.shareWebPage,
                                    size: 150.w,
                                    padding: EdgeInsets.zero,
                                  )
                                )
                              ),
                              Positioned(
                                top: 0,
                                right: 0,
                                child: controller.orderDetailData.value.status == 8 ?  Image.asset(
                                  'assets/icons/icon_written_off.png',
                                  width: 72.w,
                                  height: 72.w,
                                ) : Container()
                              )
                            ],
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 8.h),
                            padding: EdgeInsets.all(6.w),
                            decoration: BoxDecoration(
                              color: controller.orderDetailData.value.status == 8 ? pageBgColor : mainTextColor_10,
                              borderRadius: BorderRadius.circular(5.w)
                            ),
                            child: Text.rich(
                              TextSpan(
                                text: '取货劵码：',
                                style: TextStyle(
                                  color: controller.orderDetailData.value.status == 8 ? textSubtitleColor : mainTextColor,
                                  fontSize: 14.sp,
                                  fontWeight: FontWeight.bold
                                ),
                                children: [
                                  TextSpan(
                                    text: '${controller.orderDetailData.value.voucherCode}',
                                    style: TextStyle(
                                      color: controller.orderDetailData.value.status == 8 ? textSubtitleColor : mainTextColor,
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.normal
                                    ),
                                  )
                                ]
                              )
                            ),
                          )
                        ],
                      ),
                    ) : Container()
                  ],
                ),
              ),
              SizedBox(height: 12.h),
              Container(
                padding: EdgeInsets.symmetric(vertical: 8.h),
                color: bgWhiteColor,
                child: Column(
                  children: [
                    GoodsOrderInfoItem(title: '订单编号', value: '${controller.orderDetailData.value.orderSn}', showCopy: true),
                    GoodsOrderInfoItem(title: '创建时间', value: '${controller.orderDetailData.value.createdAt}'),
                  ],
                ),
              ),
              SizedBox(height: 12.h),
              Container(
                padding: EdgeInsets.only(top: 8.h),
                color: bgWhiteColor,
                child: Column(
                  children: [
                    Column(
                      children: controller.orderDetailData.value.costs!.map((item) {
                        return GoodsOrderInfoItem(title: '${item.label}', value: '${item.value}', color: '${item.color}');
                      }).toList(),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                      alignment: Alignment.centerRight,
                      height: 54.h,
                      decoration: BoxDecoration(
                        border: Border(
                          top: BorderSide(
                            color: lineColor,
                            width: .5
                          )
                        )
                      ),
                      child: Text.rich(
                        TextSpan(
                          text: controller.orderDetailData.value.status == 1 || controller.orderDetailData.value.status == 7 ?  '应付款:  ' : '实付款:  ',
                          style: TextStyle(
                            color: textBlackColor,
                            fontSize: 12.sp,
                            fontWeight: FontWeight.bold
                          ),
                          children: [
                            TextSpan(
                              text: '¥',
                              style: TextStyle(
                                color: mainTextColor,
                                fontSize: 12.sp,
                                fontWeight: FontWeight.bold
                              )
                            ),
                            TextSpan(
                              text: '${controller.orderDetailData.value.totalAmount}',
                              style: TextStyle(
                                color: mainTextColor,
                                fontSize: 16.sp,
                                fontWeight: FontWeight.bold
                              )
                            )
                          ]
                        )
                      ),
                    )
                  ],
                ),
              ),
              controller.orderDetailData.value.transfer!.length > 0 ? Container(
                color: bgWhiteColor,
                margin: EdgeInsets.only(top: 12.h),
                padding: EdgeInsets.symmetric(vertical: 8.h),
                child: Column(
                  children: controller.orderDetailData.value.transfer!.map((item) {
                    return GoodsOrderInfoItem(
                      title: '${item.label}', 
                      value: '${item.value}'
                    );
                  }).toList(),
                ),
              ) : Container(),
              controller.orderDetailData.value.status == 1 ? Obx(() => Column(
                children: [
                  Container(
                    margin: EdgeInsets.only(top: 16.h),
                    alignment: Alignment.center,
                    child: Column(
                      children: [
                        Text.rich(
                          TextSpan(
                            text: '请在',
                            style: TextStyle(
                              color: textBlackColor,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.bold
                            ),
                            children: [
                              TextSpan(
                                text: '${controller.transferRemainingTimeStr.value}分钟内',
                                style: TextStyle(
                                  color: mainTextColor,
                                  fontSize: 14.sp,
                                  fontWeight: FontWeight.bold
                                ),
                              ),
                              TextSpan(
                                text: '完成支付，',
                                style: TextStyle(
                                  color: textBlackColor,
                                  fontSize: 14.sp,
                                  fontWeight: FontWeight.bold
                                ),
                              )
                            ]
                          )
                        ),
                        SizedBox(height: 8.h),
                        Text(
                          '否则订单将会自动取消',
                          style: TextStyle(
                            color: textBlackColor,
                            fontSize: 14.sp,
                            fontWeight: FontWeight.bold
                          ),
                        )
                      ],
                    ),
                  ),
                  SizedBox(height: 33.h),
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 12.w),
                    child: Container(
                      child: ButtonUtil(
                        text: '在线客服', 
                        fontSize: 14.sp, 
                        borderRadius: 18.w, 
                        height: 36.h, 
                        onTop: () {
                          commonPageController.openWeChatCustomerServiceChat();
                        }
                      ),
                    ),
                  )
                ],
              )) : Container(),
              getTips(controller: controller)
            ],
          )),
          bottomNavigationBar: BottomAppBar(
            elevation: 0,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 12.w),
              height: controller.orderDetailData.value.status != 5 ? 56.h : 107.h,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  controller.orderDetailData.value.status != 5 ? Container() : Container(
                    margin: EdgeInsets.only(bottom: 12.h),
                    child: ButtonUtil(
                      text: '在线客服', 
                      fontSize: 14.sp, 
                      borderRadius: 36.h, 
                      height: 36.h, 
                      textColor: mainTextColor,
                      showBorder: true,
                      bgColors: [
                        bgWhiteColor,
                        bgWhiteColor,
                      ],
                      onTop: () {
                        commonPageController.openWeChatCustomerServiceChat();
                      }
                    ),
                  ),
                  StoreOrderBtns(
                    status: controller.orderDetailData.value.status!, 
                    isClick: controller.orderDetailData.value.isCheck!, 
                    pickType: controller.orderDetailData.value.pickType!,
                    voucherCode: controller.orderDetailData.value.voucherCode ?? '',
                    transferRemaining: controller.orderDetailData.value.transferRemaining ?? 0,
                    isWriteoffOfficer: commonPageController.userData.value.isWriteoffOfficer ?? 0,
                    type: controller.orderDetailData.value.type ?? 1,
                    isTransfer: controller.orderDetailData.value.isTransfer ?? 0,
                    isDetail: true,
                    toPayFun: () async {
                      var res = await Get.toNamed(
                        '${AppRouters.COMMON_PAGE}${AppRouters.GOOD_DETAIL_PAGE}${AppRouters.STORE_CONFIRM_ORDER_PAGE}${AppRouters.STORE_ORDER_PAY_PAGE}',
                        arguments: {
                          'orderId': orderId,
                          'isDetail': false
                        }
                      );
                      if (res != null && res) {
                        controller.getStoreOrderDetail(orderId);
                        if (controller.storeOrderPageController != null) {
                          controller.storeOrderPageController!.getStoreOrderList();
                        }
                      }
                    }, 
                    cleanOrderFun: () async {
                      if (controller.storeOrderPageController != null) {
                        await controller.storeOrderPageController!.storeOrderCancel(orderId);
                      }
                      controller.getStoreOrderDetail(orderId);
                    }, 
                    receiveOrderFun: () async {
                      if (controller.storeOrderPageController != null) {
                        await controller.storeOrderPageController!.storeOrderReceive(orderId);
                      }
                      controller.getStoreOrderDetail(orderId);
                    },
                    confirmReceiptFun: () {
                      if (controller.storeOrderPageController != null) {
                        controller.storeOrderPageController!.storeOrderReceive(orderId);
                      }
                    },
                    logisticsFun: () {
                      if (TextUtil.isEmpty(controller.orderDetailData.value.companyCode)) {
                        EasyLoading.showToast('快递单号异常');
                        return;
                      }
                      Get.toNamed(
                        '${AppRouters.COMMON_PAGE}${AppRouters.LOGISTICS_PAGE}',
                        arguments: {
                          'image': controller.orderDetailData.value.products![0].image,
                          'title': controller.orderDetailData.value.products![0].title,
                          'price': controller.orderDetailData.value.products![0].price,
                          'trackingNumber': controller.orderDetailData.value.trackingNumber,
                          'companyCode': controller.orderDetailData.value.companyCode,
                          'companyTitle': controller.orderDetailData.value.companyTitle
                        }
                      );
                    },
                    conversionPickingFun: () {
                      if (controller.orderDetailData.value.transferRemaining! > 0) {
                        return;
                      }
                      List<Map<String, dynamic>> mapArr = [];
                      controller.orderDetailData.value.products!.forEach((item) {
                        Map<String, dynamic> map = {
                          'image': item.image,
                          'title': item.title,
                          'price': item.price,
                          'quantity': item.quantity
                        };
                        mapArr.add(map);
                      });
                      Get.dialog(DelDialog(
                        title: '转提货',
                        message: '转提货后，商品由接受人进行提货，本人不可对订单进行操作，确认吗？', 
                        onTap: () {
                          Get.offAndToNamed(
                            '${AppRouters.COMMON_PAGE}${AppRouters.STORE_ORDER_PAGE}${AppRouters.CONVERSION_PICKING_PAGE}',
                            arguments: {
                              'orderId': orderId,
                              'products': mapArr,
                              'status': controller.orderDetailData.value.status!,
                              'statusStr': controller.orderDetailData.value.statusStr,
                            }
                          );
                        }
                      ));
                    },
                    pickUpCodeFun: () {
                      List<Map<String, dynamic>> mapArr = [];
                      controller.orderDetailData.value.products!.forEach((item) {
                        Map<String, dynamic> map = {
                          'image': item.image,
                          'title': item.title,
                          'price': item.price,
                          'quantity': item.quantity
                        };
                        mapArr.add(map);
                      });
                      Get.dialog(DelDialog(
                        title: '获取提货券码',
                        message: '获取提货券码后，不可以再转给别人提货了，确认要生成提货券码吗？', 
                        onTap: () {
                          Get.offAndToNamed(
                            '${AppRouters.COMMON_PAGE}${AppRouters.STORE_ORDER_PAGE}${AppRouters.PICKUP_CODE_PAGE}',
                            arguments: {
                              'orderId': orderId,
                              'products': mapArr,
                              'status': controller.orderDetailData.value.status!,
                              'statusStr': controller.orderDetailData.value.statusStr ?? '',
                            }
                          );
                        }
                      ));
                    },
                    seePickUpCodeFun: () {
                      
                    },
                    checkoff: () async {
                      if (controller.storeOrderPageController != null) {
                        await controller.storeOrderPageController!.checkoff(orderId);
                      }
                      controller.getStoreOrderDetail(orderId);
                    },
                  )
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  /// 商品信息
  Widget _goodsInfo(String title, String headImage, String price, int quantity, String specStr, int integral) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      color: bgWhiteColor,
      child: Row(
        children: [
          NetworkImageUtil(
            url: headImage, 
            width: 90.w, 
            height: 90.w,
            borderRadius: 5.w,
          ),
          SizedBox(width: 12.w),
          Expanded(child: Container(
            constraints: BoxConstraints(
              minHeight: 90.w
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  overflow: TextOverflow.ellipsis,
                  maxLines: 2,
                  style: TextStyle(
                    color: textBlackColor,
                    fontSize: 14.sp
                  ),
                ),
                SizedBox(height: 6.h),
                Text(
                  specStr,
                  style: TextStyle(
                    color: textSubtitleColor,
                    fontSize: 12.sp
                  ),
                ),
                SizedBox(height: 6.h),
                Row(
                  children: [
                  Expanded(child: Text(
                    '¥$price',
                    style: TextStyle(
                      color: mainTextColor,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.bold
                    )
                  )),
                  Text(
                    'x$quantity',
                    style: TextStyle(
                      color: textSubtitleColor,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.bold
                    )
                  ),
                  ],
                )
              ],
            ),
          )),
        ],
      ),
    );
  }

  Widget getTips({ required StoreOrderDetailPageController controller }) {
    if (controller.orderDetailData.value.pickType == 1 && controller.orderDetailData.value.isTransfer == 0) {
      if (controller.orderDetailData.value.status != 2 || !TextUtil.isEmpty(controller.orderDetailData.value.voucherCode)) {
        return Container();
      }
      return Container(
        margin: EdgeInsets.only(top: 20.h),
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(horizontal: 36.w),
        child: Text(
          '${controller.orderDetailData.value.tips2}',
          textAlign: TextAlign.center,
          style: TextStyle(
            color: mainTextColor,
            fontSize: 14.sp,
          ),
        )
      );
    } else {
      if (controller.orderDetailData.value.pickType == 1 && controller.orderDetailData.value.transferRemaining! > 0) {
        return Obx(() => Column(
          children: [
            Container(
              margin: EdgeInsets.only(top: 16.h),
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 36.w),
              child: Column(
                children: [
                  Text.rich(
                    TextSpan(
                      text: '${controller.tipArr.length >= 1 ? controller.tipArr[0] : ''}',
                      style: TextStyle(
                        color: textBlackColor,
                        fontSize: 14.sp
                      ),
                      children: [
                        TextSpan(
                          text: '${controller.transferRemainingTimeStr.value}',
                          style: TextStyle(
                            color: mainTextColor,
                            fontSize: 14.sp,
                            fontWeight: FontWeight.bold
                          ),
                        ),
                        TextSpan(
                          text: '${controller.tipArr.length >= 2 ? controller.tipArr[1] : ''}',
                          style: TextStyle(
                            color: textBlackColor,
                            fontSize: 14.sp
                          ),
                        )
                      ]
                    ),
                    textAlign: TextAlign.center,
                  )
                ],
              ),
            )
          ],
        ));
      } else {
        return Container();
      }
    }
  }
}